import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Scanner;

public class JDBCInsert {

    public static void main(String[] args) throws SQLException {
        DataSource dataSource = new MysqlDataSource();
        Scanner scanner = new Scanner(System.in);
        //创建并初始化一个数据源
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java107?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("111111");
        //与数据库建立连接
        Connection connection = dataSource.getConnection();
        //构造sql语句
        System.out.println("请输入姓名:");
        String name = scanner.next();
        System.out.println("请输入学号:");
        int id = scanner.nextInt();
        String sql = "insert into student values(?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,id);
        preparedStatement.setString(2,name);
        System.out.println(preparedStatement);
        //执行sql语句
        int ret = preparedStatement.executeUpdate();
        System.out.println("ret=" + ret);
        //释放必要的资源
        connection.close();
        preparedStatement.close();
    }

}
